首页 > 试题广场 >

逆波兰表达式求值

[编程题]逆波兰表达式求值
  • 热度指数:21960 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个逆波兰表达式,求表达式的值。

数据范围:表达式长度满足 ,表达式中仅包含数字和 + ,- , * , / ,其中数字的大小满足
示例1

输入

["2","1","+","4","*"]

输出

12
示例2

输入

["2","0","+"]

输出

2
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param tokens string字符串一维数组
 * @return int整型
 */
function evalRPN( tokens ) {
    // write code here
    let stack = [];
    let sum = 0;
    console.log(typeof tokens[0])
    for(let i = 0; i < tokens.length; i++) {
        if(/[0-9]/.test(tokens[i])) {
            stack.push(tokens[i]);
           
        }
        else {
            switch(tokens[i]) {
                case '+':
                    sum = parseInt(stack[stack.length-2]) + parseInt(stack[stack.length-1]);
                    stack.pop();
                    stack.pop();
                    stack.push(sum);
                    break;
                case '-':
                    sum = parseInt(stack[stack.length-2]) - parseInt(stack[stack.length-1]);
                    stack.pop();
                    stack.pop();
                    stack.push(sum);
                    break;
                case '*':
                    sum = parseInt(stack[stack.length-2]) * parseInt(stack[stack.length-1]);
                    stack.pop();
                    stack.pop();
                    stack.push(sum);
                    break;
                case '/':
                    sum = parseInt(stack[stack.length-2]) / parseInt(stack[stack.length-1]);
                    stack.pop();
                    stack.pop();
                    stack.push(sum);
                    break;
            }
        }
    }
    return stack[0];
}
module.exports = {
    evalRPN : evalRPN
};
发表于 2023-09-07 10:27:30 回复(0)

问题信息

难度:
1条回答 4847浏览

热门推荐

通过挑战的用户

查看代码